// pages/psi/analyse/dpfx/search.js
import Dialog from 'tdesign-miniprogram/dialog';
import Toast from 'tdesign-miniprogram/toast';
import moment from 'moment';

const app = getApp();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    cityText: '得一药房',
    cityValue: [],
    shopText: '全部',
    shopValue: [],
    sellerText: '',
    sellerValue: [],
    psiDistText: '',
    psiDistValue: [],
    produceText: '',
    produceValue: [],
    zxStatusText: '',
    zxStatusValue: [],
    ybStatusText: '',
    ybStatusValue: [],
    shopAttrText: '',
    shopAttrValue: [],
    citys: [
      //{ label: '全部', value: '0' },
      {
        label: '得一药房',
        value: '1'
      },
    ],
    shops: [{
        label: '全部',
        value: '0'
      },
      {
        label: '门店1',
        value: '1'
      },
      {
        label: '门店2',
        value: '2'
      },
    ],
    shopKeys: {
      label: 'shop_name',
      value: 'shop_code'
    },
    sellers: [{
      seller_name: '',
      seller_code: ''
    }],
    sellerKeys: {
      label: 'seller_name',
      value: 'seller_code'
    },
    psiDists: [{
        label: '进货',
        value: '1'
      },
      {
        label: '销售',
        value: '2'
      },
    ],
    produces: [{
        label: '产品1',
        value: '1'
      },
      {
        label: '产品1',
        value: '2'
      },
    ],
    produceKeys: {
      label: 'prd_name',
      value: 'prd_code'
    },
    years: [{
        label: '2021年',
        value: '2021'
      },
      {
        label: '2020年',
        value: '2020'
      },
      {
        label: '2019年',
        value: '2019'
      },
    ],
    seasons: [{
        label: '1月',
        value: '1'
      },
      {
        label: '2月',
        value: '2'
      },
      {
        label: '3月',
        value: '3'
      },
      {
        label: '4月',
        value: '4'
      },
      {
        label: '5月',
        value: '5'
      },
      {
        label: '6月',
        value: '6'
      },
      {
        label: '7月',
        value: '7'
      },
      {
        label: '8月',
        value: '8'
      },
      {
        label: '9月',
        value: '9'
      },
      {
        label: '10月',
        value: '10'
      },
      {
        label: '11月',
        value: '11'
      },
      {
        label: '12月',
        value: '12'
      },
    ],
    zxStatuses: [{
        label: '全部',
        value: ''
      },
      {
        label: '线上',
        value: '1'
      },
      {
        label: '线下',
        value: '2'
      },
    ],
    ybStatuses: [{
        label: '全部',
        value: ''
      },
      {
        label: '医保',
        value: '1'
      },
      {
        label: '非医保',
        value: '2'
      },
    ],
    shopAttrs: [{
        label: '全部',
        value: ''
      },
      {
        label: '院边店',
        value: '1'
      },
      {
        label: '社区店',
        value: '2'
      },
      {
        label: '商业店',
        value: '3'
      },
    ],
    mode: '',
    dayBeginVisible: false,
    dayEndVisible: false,
    dayBegin: new Date().getTime(), // 支持时间戳传入
    dayEnd: new Date().getTime(), // 支持时间戳传入
    dayBeginText: moment().add(-7, 'days').format('YYYY-MM-DD'),
    dayEndText: moment().format('YYYY-MM-DD'),
    // 指定选择区间起始值
    start: '2000-01-01 00:00:00',
    end: '2030-09-09 12:12:12',
    downloadLink: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 检验是否登录
    app.checkLogin();

    // 获取字典
    console.log('---onLoad---');

    // 记录操作日志
    app.api.log({
      title: '数据分析-店铺分析',
      message: 'success',
    })

    this.getDistShop();
    this.getDistSeller();
    this.getDistProduce();
  },
  copyText(e) {
    let key = e.currentTarget.dataset.key;
    wx.setClipboardData({
      //设置系统剪贴板的内容
      data: key,
      success(res) {
        console.log(res, key);
        wx.getClipboardData({
          // 获取系统剪贴板的内容
          success(res) {
            wx.showToast({
              title: '复制成功',
            });
          },
        });
      },
    });
  },
  getDistShop() {
    console.log('getDistShop');
    wx.request({
      url: 'https://sst.jmit.cn/api_sst/getDistShop.aspx',
      data: '',
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
      },
      success: (request) => {
        console.log('getDistShop的结果', request.data);
        const res = request.data;
        //app.globalData.userInfo = res.data.data;//
        //var data = JSON.parse(res.data);

        if (res.code == 200) {
          this.setData({
            shops: res.data
          });
        } else {}
      },
      fail(res) {
        console.log(res.erMsg);
      },
    });
  },
  getDistSeller() {
    console.log('getDistSeller');
    wx.request({
      url: 'https://sst.jmit.cn/api_sst/getDistSeller.aspx',
      data: '',
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
      },
      success: (request) => {
        console.log('getDistSeller的结果', request.data);
        const res = request.data;
        //app.globalData.userInfo = res.data.data;//
        //var data = JSON.parse(res.data);

        if (res.code == 200) {
          this.setData({
            sellers: res.data
          });
        } else {}
      },
      fail(res) {
        console.log(res.errMsg);
      },
    });
  },
  getDistProduce() {
    console.log('getDistProduce');
    wx.request({
      url: 'https://sst.jmit.cn/api_sst/getDistPrd.aspx',
      data: '',
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
      },
      success: (request) => {
        console.log('getDistProduce的结果', request.data);
        const res = request.data;
        //app.globalData.userInfo = res.data.data;//
        //var data = JSON.parse(res.data);

        if (res.code == 200) {
          this.setData({
            produces: res.data
          });
        } else {}
      },
      fail(res) {
        console.log(res.erMsg);
      },
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  onColumnChange(e) {
    console.log('picker pick:', e);
  },

  onPickerChange(e) {
    const {
      key
    } = e.currentTarget.dataset;
    const {
      value,
      label
    } = e.detail;

    console.log('picker change:', e.detail);
    this.setData({
      [`${key}Visible`]: false,
      [`${key}Value`]: value,
      [`${key}Text`]: label.join(' '),
    });
  },

  onPickerCancel(e) {
    const {
      key
    } = e.currentTarget.dataset;
    console.log(e, '取消');
    console.log('picker1 cancel:');
    this.setData({
      [`${key}Visible`]: false,
    });
  },

  onCityPicker() {
    this.setData({
      cityVisible: true
    });
  },

  onShopPicker() {
    this.setData({
      shopVisible: true
    });
  },

  onSellerPicker() {
    this.setData({
      sellerVisible: true
    });
  },

  onPsiDistPicker() {
    this.setData({
      psiDistVisible: true
    });
  },

  onProducePicker() {
    this.setData({
      produceVisible: true
    });
  },

  onSeasonPicker() {
    this.setData({
      dateVisible: true
    });
  },

  onZxStatusPicker() {
    this.setData({
      zxStatusVisible: true
    });
  },

  onYbStatusPicker() {
    this.setData({
      ybStatusVisible: true
    });
  },

  onShopAttrPicker() {
    this.setData({
      shopAttrVisible: true
    });
  },

  showPicker(e) {
    const {
      mode
    } = e.currentTarget.dataset;
    this.setData({
      mode,
      [`${mode}Visible`]: true,
    });
  },
  hidePicker() {
    const {
      mode
    } = this.data;
    this.setData({
      [`${mode}Visible`]: false,
    });
  },
  onConfirm(e) {
    const {
      value
    } = e.detail;
    const {
      mode
    } = this.data;

    console.log('confirm', value);

    this.setData({
      [mode]: value,
      [`${mode}Text`]: value,
    });

    this.hidePicker();
  },

  onColumnChange(e) {
    console.log('pick', e.detail.value);
  },

  // 查询
  submitQuery() {
    console.log('submitQuery');
    const {
      cityText,
      cityValue,
      shopText,
      shopValue,
      dayBeginText,
      dayEndText
    } = this.data;
    // const { goodsRequestList } = this;

    console.log(!shopText);
    console.log(shopValue);

    if (!shopText && shopValue.length === 0) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '请选择门店',
        duration: 2000,
        icon: 'help-circle',
      });

      return;
    }

    wx.navigateTo({
      url: `/pages/psi/analyse/dpfx/result?shop_code=${shopValue}&day_begin=${dayBeginText}&day_end=${dayEndText}`,
    });
  },

  // 导出
  submitExport() {
    this.getUrl();
    //this.downloadFile('https://sst.jmit.cn/api_sst/out/out_20231204050504.csv'); // 下载文件
  },
  async getUrl() {
    const {
      cityValue,
      shopText,
      shopValue,
      produceText,
      produceValue,
      dayBeginText,
      dayEndText
    } = this.data;
    // const { goodsRequestList } = this;

    // if (shopValue.length === 0) {
    //   Toast({
    //     context: this,
    //     selector: '#t-toast',
    //     message: '请选择门店',
    //     duration: 2000,
    //     icon: 'help-circle',
    //   });

    //   return;
    // }

    if (produceText.length === 0) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '请选择产品',
        duration: 2000,
        icon: 'help-circle',
      });

      return;
    }

    if (!dayBeginText && dayBeginText.length === 0) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '请选择开始时间',
        duration: 2000,
        icon: 'help-circle',
      });

      return;
    }

    if (!dayEndText && dayEndText.length === 0) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '请选择结束时间',
        duration: 2000,
        icon: 'help-circle',
      });

      return;
    }

    try {
      console.log('submitOrder');

      const {
        shopValue,
        produceValue,
        sellerValue,
        dayBegin,
        dayEnd
      } = this.data;
      console.log('dayBegin:', dayBegin);
      console.log('dayBegin:', dayEnd);
      const result = await this.getSearchResult({
        customer_code: '',
        shop_code: shopValue,
        prd_code: produceValue,
        seller_code: sellerValue,
        day_begin: dayBegin,
        day_end: dayEnd,
      });

      const code = result.code;
      const outputUrl = result.data?.outputUrl;

      console.log('1111', outputUrl);
      if (code === 200) {
        // const { spuList, totalCount = 0 } = data;

        console.log('导出地址：', outputUrl);

        if (!outputUrl) {
          wx.showToast({
            title: '未找到相关数据，请稍候重试',
          });

          return;
        }

        wx.showToast({
          title: '数据已生成',
        });
        console.log('生成完成:' + outputUrl);
        this.setData({
          downloadLink: outputUrl,
        });

        //this.downloadFile(outputUrl); // 下载文件
      } else {
        this.setData({
          loading: false,
        });
        wx.showToast({
          title: '未找到相关数据，请稍候重试',
        });
      }
    } catch (error) {
      this.setData({
        loading: false,
      });
    }
  },
  async downloadFile(outUrl) {
    //const filePath = `${wx.env.USER_DATA_PATH}/out_20231204050317.csv`;
    var fileName = outUrl.substring(outUrl.lastIndexOf('/') + 1, outUrl.lastIndexOf('.'));
    //var fileName = outUrl.substring(outUrl.lastIndexOf('/') + 1);

    // fileName = 'out_20231204050317';
    // outUrl = 'https://sst.jmit.cn/api_sst/out/out_20231204050317.csv';

    console.log('outUrl:' + outUrl);
    console.log(outUrl.lastIndexOf('/') + 1);
    console.log('fileName:' + fileName);
    wx.downloadFile({
      url: outUrl,
      // 1. 必须带有这个wx.env.USER_DATA_PATH，表示存储在用户本地 ！！！
      // fileName表示自定的文件名称
      // 实际在PC端调试存储位置为类似 C:\Users\SJshe\AppData\Local\微信开发者工具\User Data\WeappFileSystem\o6zAJs3c0u3SeBVn_9MUgG6UZJ1M\wx2efdf4edd8bccb88
      filePath: wx.env.USER_DATA_PATH + '/' + fileName,
      success: function (res) {
        if (res.statusCode === 200) {
          // wx.showToast({
          //   title: '下载完成',
          // });
          // console.log('下载完成:' + res.filePath);
          // this.setData({
          //   downloadLink: res.filePath,
          // });
          // wx.openDocument({
          //   filePath: res.filePath,
          //   fileType: ['docx'], // 2. xlsx 这个必须写合法类型，不然下载不了(个人认为官方应该特别说明) ！！！
          //   success: function (res) {
          //     console.log('打开文档成功');
          //   },
          //   fail: function (e) {
          //     console.log('打开文档失败');
          //     console.log(e.errMsg);
          //   },
          // });
        }
      },
      fail: function (e) {
        // 强烈建议打印失败原因，便于排查
        console.log(e.errMsg);
      },
    });
  },

  getSearchResult(params) {
    console.log('getSearchResult');

    console.log(params);

    return new Promise(function (resolve, reject) {
      wx.request({
        url: 'https://sst.jmit.cn/api_sst/getDataSellToCSV.aspx',
        //data: 'shop_code=' + this.data.shop_code + '&prd_code=' + this.data.prd_code,
        data: params,
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
        },
        success: (request) => {
          console.log('getDistProduce的结果', request.data);
          const res = request.data;
          //app.globalData.userInfo = res.data.data;//
          //var data = JSON.parse(res.data);

          resolve(res);
          // if (res.code == 200) {
          //   this.setData({ produces: res.data });
          // } else {
          // }
        },
        fail(res) {
          console.log(res);
          reject(err);
        },
      });
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
});